<template>
  <div class="app-container">

    <YxhyTableQuery :query-params.sync="queryParams" :query-columns="queryColumns" @search="handleQuery">
      <template #selectRemote>
        <YxhySelectRemote
          :value.sync="queryParams.library_id"
          :request-fn="queryNonSortLibrary"
          :request-key="`title_search`"
          :response-id="`library_id`"
          :response-name="`title`"
          :placeholder="`请输入短剧名称`"
        />
      </template>
      <el-form-item slot="button">
        <el-button v-hasPermi="['config:banner:add']" type="success" @click="handleAdd">添加轮播图</el-button>
      </el-form-item>
    </YxhyTableQuery>

    <YxhyTableData :columns="columns" :data="tableList" :loading="loading">
      <!-- 轮播图插槽 -->
      <template #image_url>
        <el-table-column label="轮播图" align="center" width="200">
          <template slot-scope="{ row }">
            <el-image
              style="width: auto; height: 100px"
              :src="row.oss_object.url || ''"
              :preview-src-list="[row.oss_object.url]"
              fit="cover"
            />
          </template>
        </el-table-column>
      </template>
      <!-- 跳转剧集插槽 -->
      <template #episode_name>
        <el-table-column label="跳转剧集" align="center" width="auto">
          <template slot-scope="{ row }">
            <p class="font-color-td">{{ row.library_name | domEmpty }}</p>
            <p class="font-color-td">{{ row.episode_name | domEmpty }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 创建时间插槽 -->
      <template #created_at>
        <el-table-column label="创建时间" align="center" :width="columnDateTimeWidth()">
          <template slot-scope="{ row }">
            <p class="font-color-td width-create-time">{{ row.created_at }}</p>
          </template>
        </el-table-column>
      </template>
      <!-- 插槽内容 -->
      <template #action>
        <el-table-column label="操作" align="center" width="80">
          <template slot-scope="scope">
            <div class="table-action-panel">
              <template v-if="scope.row.flag == 1">
                <el-button v-hasPermi="['config:banner:flag']" type="danger" size="mini" @click="handleUpdateFlag(scope.row, 0)">下架</el-button>
              </template>
              <template v-else>
                <el-button v-hasPermi="['config:banner:flag']" type="success" size="mini" @click="handleUpdateFlag(scope.row, 1)">上架</el-button>
              </template>
              <el-button v-hasPermi="['config:banner:edit']" type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            </div>
          </template>
        </el-table-column>
      </template>
    </YxhyTableData>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryPage.pageNum"
      :limit.sync="queryPage.limit"
      @pagination="init"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="轮播图名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入轮播图名称" />
        </el-form-item>
        <el-form-item label="轮播图" prop="image_id">
          <ImageUploadOss ref="imageUploadOssRef" :oss-id.sync="form.image_id" :value="form.image" :limit="1" />
          <p class="font-12" style="color: #606266; line-height: 1">轮播图尺寸：345px * 150px</p>
        </el-form-item>
        <el-form-item label="跳转链接" prop="url">
          <el-input v-model="form.url" placeholder="请输入小程序页面路由，若跳转剧集则不填写" />
        </el-form-item>
        <el-form-item label="跳转短剧" prop="library_id">
          <YxhyTableDialogSelect
            :btn-text="`选择短剧`"
            :table-key="`library_id`"
            :table-name="`title`"
            :detail-data="formDetail"
            :detail-id-key="`library_id`"
            :columns="columnsSelectLibrary"
            :query-params="queryParamsSelectLibrary"
            :query-columns="queryColumnsSelectLibrary"
            :request-fn="queryNonSortLibrary"
            @selectResult="handleSelectResultLibrary"
          />
        </el-form-item>
        <el-form-item label="跳转剧集" prop="episode_id">
          <YxhySelect :value.sync="form.episode_id" :columns="episodeColumns" />
        </el-form-item>
        <el-form-item label="关联小程序" prop="library_id">
          <YxhyTableDialogSelect
            :btn-text="`选择小程序`"
            :table-key="`product_id`"
            :table-name="`product_name`"
            :detail-data="formDetail"
            :detail-id-key="`app_id`"
            :columns="columnsSelectMp"
            :query-params="queryParamsSelectMp"
            :query-columns="queryColumnsSelectMp"
            :request-fn="queryListNonSortMp"
            @selectResult="handleSelectResultMp"
          />
          <p class="font-color-2 font-14">不选则默认全部小程序生效</p>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="排序越小越靠前" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryListLibrary, queryNonSortLibrary, queryTotalEpisode } from '@/api/video/library.js'
import { queryListBanner, addBanner, editBanner, updateFlagBanner, FLAG } from '@/api/miniProgram/banner.js'
import { columnsSelectLibrary, columnsSelectMp, columnsStatic } from './Ds.js'
import { queryListMp, queryListNonSortMp } from '@/api/miniProgram/mp'
import { deepClone } from '@/utils'

export default {
  name: 'BannerList',
  data() {
    return {
      // 总条数
      total: 0,
      // 表格数据
      tableList: [],
      // 分页参数
      queryPage: {
        pageNum: 1,
        limit: 10
      },
      // 查询参数
      queryParams: {
        title: undefined,
        library_id: undefined,
        flag: undefined
      },
      // 查询表单
      queryColumns: [{
        label: '',
        placeholder: '请输入轮播图名称',
        type: 'input',
        param: 'title'
      }, {
        label: '',
        placeholder: '请输入短剧名称',
        type: 'selectRemote',
        param: 'library_id'
      }, {
        label: '',
        placeholder: '请选择状态',
        type: 'select',
        selectOptions: [{ name: '已上架', value: 1 }, { name: '未上架', value: 0 }],
        param: 'flag'
      }],

      loading: false,
      // 表格列
      columns: columnsStatic,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {
        title: undefined,
        image: undefined,
        image_id: undefined,
        url: undefined,
        episode_id: undefined,
        library_id: undefined,
        app_id: undefined,
        sort: undefined
      },
      formDetail: null,
      // 表单校验
      rules: {
        title: [
          { required: true, message: '请输入轮播图名称', trigger: ['blur', 'change'] }
        ],
        image_id: [
          { required: true, message: '请选择轮播图', trigger: ['blur', 'change'] }
        ]
      },

      // 选择短剧
      queryParamsSelectLibrary: {
        library_id_search: undefined,
        title_search: undefined
      },
      queryColumnsSelectLibrary: [
        {
          label: '',
          placeholder: '请输入短剧ID',
          type: 'input',
          param: 'library_id_search'
        }, {
          label: '',
          placeholder: '请输入短剧名称',
          type: 'input',
          param: 'title_search'
        }
      ],
      columnsSelectLibrary,
      queryListLibrary,
      queryNonSortLibrary,

      // 跳转剧集
      episodeColumns: [],

      // 关联小程序
      queryParamsSelectMp: {
        product_id_search: undefined,
        product_name_search: undefined
      },
      queryColumnsSelectMp: [
        {
          label: '',
          placeholder: '请输入id',
          type: 'input',
          param: 'product_id_search'
        }, {
          label: '',
          placeholder: '请输入小程序名称',
          type: 'input',
          param: 'product_name_search'
        }
      ],
      columnsSelectMp,
      queryListMp,
      queryListNonSortMp
    }
  },
  computed: {
    isEdit() {
      return ![undefined, ''].includes(this.form.id)
    }
  },
  created() {
    this.init()
  },
  methods: {
    async init() {
      this.loading = true
      this.queryParams.flag = this.queryParams.flag === '' ? undefined : this.queryParams.flag
      this.queryParams.library_id = this.queryParams.library_id === '' ? undefined : this.queryParams.library_id
      const res = await queryListBanner({
        ...this.queryPage,
        ...this.queryParams
      })
      res.data.map(e => {
        const { flag } = e
        e.episode_name = e.episode_name || '-'
        e.url = e.url || '-'
        e.admin_username = e.admin_username || '-'
        e.app_name = e.app_name.length > 0 ? e.app_name : '-'
        e.flag_text = FLAG[flag]
        e.oss_object = e.oss_object || {}
      })
      this.tableList = res.data
      this.total = res.total
      this.loading = false
    },
    /** 根据已选择短剧，查询剧集库 */
    async queryTotalEpisodeFn() {
      if (!this.form.library_id) return

      const res = await queryTotalEpisode({
        library_id: this.form.library_id
      })
      const arr = res.map(e => {
        const { episode_id, episode } = e
        return { value: episode_id, label: `第${episode}集` }
      })
      this.episodeColumns = arr
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        title: undefined,
        image: undefined,
        image_id: undefined,
        url: undefined,
        episode_id: undefined,
        library_id: undefined,
        app_id: undefined,
        sort: undefined
      }
      this.resetForm('formRef')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryPage.pageNum = 1
      this.init()
    },
    /** 清空搜索按钮操作 */
    handleClear() {
      this.queryParams = {
        library_id_search: undefined,
        title_search: undefined,
        classify_search: undefined,
        is_publish_search: undefined
      }
      this.init()
    },
    /** 接收短剧选择 */
    handleSelectResultLibrary(rows) {
      const library_id_str = rows.map(item => item.library_id).toString()
      this.form.library_id = library_id_str

      if (this.form.library_id) {
        this.queryTotalEpisodeFn()
      } else {
        this.episodeColumns = []
        this.form.episode_id = undefined
      }
    },
    /** 接收小程序选择 */
    handleSelectResultMp(rows) {
      const is_str = rows.map(item => item.product_id).toString()
      this.form.app_id = is_str
    },
    /** 上架&下架按钮操作 */
    handleUpdateFlag(row, flag) {
      const { id } = row
      updateFlagBanner({
        id,
        flag
      }).then(() => {
        this.$modal.msgSuccess('操作成功')
        this.open = false
        this.handleQuery()
      })
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.title = '添加轮播图'
      this.$nextTick(() => {
        this.reset()
        this.formDetail = null
        this.$refs.imageUploadOssRef?.resetFileList()
      })
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.open = true
      this.title = '修改轮播图'

      this.reset()
      row.image = row.oss_object.url
      row.url = row.url === '-' ? undefined : row.url

      this.form = deepClone(row)
      this.$nextTick(() => {
        // 组件watch监听formDetail变量，去请求接口，保证dom上已经渲染完毕
        this.formDetail = deepClone(row)
      })

      await this.queryTotalEpisodeFn()
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['formRef'].validate((valid) => {
        if (valid) {
          this.form.library_id = this.form.library_id === '' ? undefined : this.form.library_id
          if (this.form.id != undefined) {
            editBanner(this.form).then(res => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.init()
            })
          } else {
            addBanner(this.form).then(res => {
              this.$modal.msgSuccess('添加成功')
              this.open = false
              this.init()
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.component-upload-image {
  ::v-deep .el-upload--picture-card {
    width: 200px;
    height: 100px;
    line-height: 100px;
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item{
    width: auto;
    height: 100px;
  }
}
</style>
